package com.gem.taskplan.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gem.taskplan.adapter.MemberListAdapter;
import com.gem.taskplan.service.BackAcitvity;
import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.DialogTool;
import com.gem.taskplan.service.JsonPackage;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;
import com.gem.taskplan.util.Tools;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class TaskActivity extends FragmentActivity {

	private String url = "/TaskServlet";
	private String url1 = "/SetServlet";
	private String attachmenturl = "/UploadingServlet";
	private ViewPager my_vp;
	private Fragment fragment1,fragment2,fragment3;
	FragmentManager fm;
	FragmentTransaction ft;
	//页面列表
	private ArrayList<Fragment> fragmentList;
	//标题列表
	private ArrayList<String>   titleList    = new ArrayList<String>();
	//通过pagerTabStrip可以设置标题的属性
	private PagerTabStrip pagerTabStrip;

	/********控件名**********/
	public static final int FILE_RESULT_CODE = 1;
	private ImageView addTask;
	private ImageView back;
	private LayoutInflater inflater;
	private ListView addUserListView;
	private MemberListAdapter memberListAdapter;
	private MemberListAdapter memberListAdapter1;
	private List<Map<String, String>> list  = new ArrayList<Map<String,String>>();
	private List<Map<String, String>> list1  = new ArrayList<Map<String,String>>();
	private ListView task_members;//被选中的成员list列表
	private Set<String> setStrings = new TreeSet<String>();//用来存储被关联的成员名字
	private Set<String> setNumber = new TreeSet<String>();//用来存储被关联的成员名字
	private View addMemberView;//添加成员的布局视图
	private ImageView addAttachment ;//添加附件按钮
	private TextView taskAttachmentName ;//附件名
	private TextView titleText;
	private String curProjectName;
	private String curUser;
	private String curTeam;
	private Button sureAddTask;
	private Button cancelAddTask;
	StringBuffer buffer = new StringBuffer();
	Bundle bundle;
	String content;
	String endtime;
	String member;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task);

		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);

		/************获得访问服务器的地址***************/
		url = PropertiesUtil.getServerURL(this)+url;
		url1 = PropertiesUtil.getServerURL(this)+url1;
		attachmenturl = PropertiesUtil.getServerURL(this)+attachmenturl;
		/********获取上个界面的传值*********/
		Intent intent = getIntent();
		curProjectName = intent.getStringExtra("projectName");
		curTeam = intent.getStringExtra("teamName");
		curUser = getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE).getString("lastUser", "");
		Toast.makeText(this, curTeam, Toast.LENGTH_SHORT).show();
		/********初始化控件*********/
		addTask = (ImageView) findViewById(R.id.addTask);
		back = (ImageView) findViewById(R.id.backWorkTable);
		my_vp = (ViewPager)findViewById(R.id.viewpager);
		pagerTabStrip=(PagerTabStrip) findViewById(R.id.pagertab);
		inflater = getLayoutInflater();
		titleText = (TextView) findViewById(R.id.titleText);
		titleText.setText(curProjectName);
		//设置下划线的颜色
		pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.tab_indicator_text)); 
		//设置背景的颜色
		pagerTabStrip.setBackgroundColor(getResources().getColor(android.R.color.transparent));

		fragment1 = new Fragment1(TaskActivity.this,bundle,curProjectName,curTeam);
		fragment2 = new Fragment2(TaskActivity.this,bundle,curProjectName,curTeam);
		fragment3 = new Fragment3(TaskActivity.this,bundle,curProjectName,curTeam) ;

		fragmentList = new ArrayList<Fragment>();
		fragmentList.add(fragment1);
		fragmentList.add(fragment2);
		fragmentList.add(fragment3);

		titleList.add("待做");
		titleList.add("在做");
		titleList.add("完成 ");

		my_vp.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));

		//fragment的滑动监听
		my_vp.setOnPageChangeListener(new My_vpOnPageChange());

		//为项目添加新任务监听
		addTask.setOnClickListener(new ImageAddTaskOnClick());

		//返回监听,调用服务层代码完成
		BackAcitvity.back(back, TaskActivity.this);

		//设置适配器
		//simpleAdapter = new SimpleAdapter(this,list, R.layout.choose_member_list,new String[]{"image","name"}, new int[]{R.id.choosed1,R.id.memberName});
		memberListAdapter = new MemberListAdapter(list, TaskActivity.this, R.layout.choose_member_list);
		memberListAdapter1 = new MemberListAdapter(list1, TaskActivity.this, R.layout.choose_member_list1);
		//list.clear();//初始化时每次数据先清空再加载
		initMembersList();

	}

	/*********跳转回写的结果值**************/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println("***************进入回调方法！！！！！！！！！"+"requestcod="+requestCode+",resultcode="+resultCode);


		Fragment1.initFragment1();//初始化fragment1的显示界面
		Fragment2.initFragment2();//初始化fragment2的显示界面
		Fragment3.initFragment3();//初始化fragment3的显示界面

		if(FILE_RESULT_CODE == requestCode){
			Bundle bundle = null;
			if(data!=null&&(bundle=data.getExtras())!=null){
				String pathName = bundle.getString("file");
				taskAttachmentName.setText(pathName);
			}
		}
	}

	/***************************************所有监听事件实现类***************************************/


	/********************为项目添加新任务**************************/
	public class ImageAddTaskOnClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			//清空
			list1.clear();
			initMembersList();
			//
			View dialogView = inflater.inflate(R.layout.add_task_dialog, null);//外层
//			
//			LinearLayout layout = (LinearLayout) dialogView.findViewById( R.id.addTaskLayout);
			View addTaskView = inflater.inflate(R.layout.add_task_config, null);//内嵌布局
			sureAddTask = (Button) dialogView.findViewById(R.id.sureAddTask);
			cancelAddTask = (Button) dialogView.findViewById(R.id.cancelAddTask);
//			layout.addView(addTaskView);


			//			members = (TextView) addTaskView.findViewById(R.id.task_members);
			task_members = (ListView) dialogView.findViewById(R.id.task_members);
			task_members.addHeaderView(addTaskView);
			//设置适配器
			task_members.setAdapter(memberListAdapter1);
			final EditText taskName = (EditText) addTaskView.findViewById(R.id.task_Name);
			final DialogTool tool = new DialogTool(TaskActivity.this);
			final TextView editText = (TextView) addTaskView.findViewById(R.id.outOfTime_et);
			TextView timeTv = (TextView) addTaskView.findViewById(R.id.timeTv);
			final int curItem = my_vp.getCurrentItem();
			if(curItem==2){
				timeTv.setText("完成时间");
			}
			RelativeLayout time = (RelativeLayout) addTaskView.findViewById(R.id.time);
			tool.getTimeDialog(editText,time);//设置监听弹出事件选择器
			ImageView addMembers = (ImageView) addTaskView.findViewById(R.id.addTask_members);//添加成员按钮
			addAttachment = (ImageView) addTaskView.findViewById(R.id.addTask_attachment);//添加附件按钮
			taskAttachmentName = (TextView) addTaskView.findViewById(R.id.task_attachment);//附件名
			//添加附件按钮的监听   
			addAttachment.setOnClickListener(new ImageAddAttachmentOnClick());
			//关联成员按钮的监听
			addMembers.setOnClickListener(new AddMemberOnclick());
			final Dialog dialog = new Dialog(TaskActivity.this);
			dialog.setContentView(dialogView);
//			dialog.setIcon(android.R.drawable.ic_input_add);
//			dialog.setFeatureDrawable(featureId, drawable)
			dialog.setTitle("添加新任务");
			WindowManager m = getWindowManager(); 
			Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
//			Window window = dialog.getWindow();//获取对话框当前的参数值 
			Window window = dialog.getWindow();//获取对话框当前的参数值 
			WindowManager.LayoutParams lp = window.getAttributes();
			lp.height = (int) (d.getHeight() * 0.87); // 高度设置为屏幕的0.6
			lp.width = (int) (d.getWidth() * 0.9); // 宽度设置为屏幕的0.65
			window.setAttributes(lp);
			dialog.show();
//			final AlertDialog dialog = new AlertDialog.Builder(TaskActivity.this);
//			.setIcon(android.R.drawable.ic_input_add).setTitle("添加新任务").setView(addTaskView).create();
//			dialog.show();
			sureAddTask.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {

					//获取添加任务内的内容
					content = taskName.getText().toString();
					if(content==null|content.trim().length()==0){
						Toast.makeText(TaskActivity.this, "任务名不能为空", Toast.LENGTH_SHORT).show();
						return;
					}
					endtime = editText.getText().toString();
					if(endtime==null|endtime.trim().length()==0){
						Toast.makeText(TaskActivity.this, "请您设置截止时间", Toast.LENGTH_SHORT).show();
						return;
					}

					buffer.delete(0,buffer.length());
					for(String name : setStrings){
						buffer.append(name).append(" | ");
					}
					buffer.delete(buffer.length()-2, buffer.length()-1);
					member = buffer.toString();
					if(member==null|member.trim().length()==0){
						Toast.makeText(TaskActivity.this, "设置成员", Toast.LENGTH_SHORT).show();
						return;
					}
					String path = taskAttachmentName.getText().toString();

					String attachment = path;
					//					if(attachment.length()==0){attachment="";}
					String[] key = new String[]{"content","member","attachment","endtime","curProjectName","curUser"}; 
					String[] value = new String[]{content,member,attachment,endtime,curProjectName,curUser};
					String jasonObject = JsonPackage.getJson("taskInfo",value, key);

					System.out.println("jason封装数据："+jasonObject);

					Map<String , String> map = new HashMap<String, String>();
					map.put("task", jasonObject);

					if(curItem == 0){
						map.put("action", "addTodo");
					}else if(curItem==1){
						map.put("action", "addDoing");
					}else if(curItem==2){
						map.put("action", "addDone");
					}else {
						Toast.makeText(TaskActivity.this, "添加任务的action参数异常！" , Toast.LENGTH_SHORT).show();
						return;
					}
					//验证时否联网
					if(!CheckedNetWork.checkedConnection(TaskActivity.this)){
						return;
					}

					String result = null;
					try {
						map.put("curUser", curUser);
						result = HttpUtil.postRequest(url, map);
						System.out.println("+++++++++++++++++"+result);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(result.equals("yes")){
						/************上传附件，请求服务器**********************/
						if(path.equals("附件名")){

						}else {
							if(new File(path).isFile()){//如果是文件就请求上传
								uploadAttachment(path, content);
							}
						}

						Toast.makeText(TaskActivity.this, "添加任务成功", Toast.LENGTH_LONG).show();
						bundle = new Bundle();
						bundle.putString("content", content);
						bundle.putString("endtime", endtime);
						bundle.putString("member", member);
						if(path.equals("附件名")){

						}else {
							File file = new File(path);
							if(file.isFile()){
								bundle.putString("attachment", "1");
							}else {
								bundle.putString("attachment", "0");
							}
						}

						if(curItem == 0){
							Fragment1.setData1(bundle);
						}else if(curItem==1){
							Fragment2.setData2(bundle);
						}else if(curItem==2){
							Fragment3.setData3(bundle);
						}else {
							Toast.makeText(TaskActivity.this, "获取当前页面Item异常！" , Toast.LENGTH_SHORT).show();
							return;
						}

					}else {
						Toast.makeText(TaskActivity.this, "返回值是非真", Toast.LENGTH_LONG).show();
					}
					dialog.cancel();
				}
			});
			cancelAddTask.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.cancel();
				}
			});
		}

	}

	/************上传附件，请求服务器**********************/
	private void uploadAttachment(String path,String taskName){
		AjaxParams params = new AjaxParams();
		params.put("action", "attachment");
		params.put("taskName", taskName);
		Toast.makeText(TaskActivity.this,taskName, Toast.LENGTH_SHORT).show();
		//System.err.println("############################"+taskName.getText().toString());
		//		File file = new File(path);
		try {
			params.put("AttachmentPath", new File(path));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		FinalHttp fh = new FinalHttp();
		fh.configCharset(HTTP.UTF_8);
		fh.post(attachmenturl, params, new AjaxCallBack<String>() {
			@Override
			public void onSuccess(String t) {
				Toast.makeText(TaskActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
				super.onSuccess(t);
			}
			@Override
			public void onFailure(Throwable t, String strMsg) {
				Toast.makeText(TaskActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {
				Toast.makeText(TaskActivity.this, "正在上传！", Toast.LENGTH_SHORT).show();
				super.onLoading(count, current);
			}
		});
	}


	/******************添加附件按钮的监听***********************/
	public class ImageAddAttachmentOnClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(TaskActivity.this,SDFileManagerActivity.class);
			startActivityForResult(intent, FILE_RESULT_CODE);
		}
	}


	/******************关联成员按钮的监听***********************/
	public class AddMemberOnclick implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			System.out.println("进入 关联成员按钮的监听");

			addMemberView = inflater.inflate(R.layout.base_user_dialog, null);
			addUserListView = (ListView) addMemberView.findViewById(R.id.userList);
			Button sure = (Button) addMemberView.findViewById(R.id.sure);
			Button cancel = (Button) addMemberView.findViewById(R.id.cancel);
			addUserListView.setAdapter(memberListAdapter);
			//			System.out.println(curUserName);

			//成员列表addUserListView的监听
			addUserListView.setOnItemClickListener(new AddTaskMemberOnItemClick());
			
			final Dialog dialog = new AlertDialog.Builder(TaskActivity.this).setView(addMemberView).create();
			dialog.show();
			sure.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					System.out.println("set集合 = "+setStrings.size());
					StringBuffer buffer = new StringBuffer() ;

					list1.clear();
					for(String member :setNumber){
						int position = Integer.parseInt(member);
						Map<String, String> map1 = list.get(position);
						//System.out.println("$$$$$$$$"+map1.get("checked"));
						list1.add(map1);
					}
					memberListAdapter1.notifyDataSetChanged();
				
					dialog.cancel();
				}
			});
			cancel.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
			
			
			
			//弹出成员选择的窗口
			
			/*setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					System.out.println("set集合 = "+setStrings.size());
					StringBuffer buffer = new StringBuffer() ;

					list1.clear();
					for(String member :setNumber){
						int position = Integer.parseInt(member);
						Map<String, String> map1 = list.get(position);
						//System.out.println("$$$$$$$$"+map1.get("checked"));
						list1.add(map1);
					}
					memberListAdapter1.notifyDataSetChanged();
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			}).create().show();*/

//			setNumber.clear();
//			setStrings.clear();

		}
	}

	/************************成员列表addUserListView的监听*****************************/
	public class AddTaskMemberOnItemClick implements AdapterView.OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			System.out.println("进入成员列表addUserListView的监听");
			ImageView imageView =  (ImageView) view.findViewById(R.id.choosed1);
			//String name = list.get(position).get("name");
			Map<String, String> map = null;
			map = list.get(position);
			if(imageView.getVisibility()==View.VISIBLE){
				imageView.setVisibility(View.INVISIBLE);
				map.put("checked", "0");
				setNumber.remove(String.valueOf(position));
				setStrings.remove(map.get("name"));
			}else {
				imageView.setVisibility(View.VISIBLE);
				map.put("checked", "1");
				setNumber.add(String.valueOf(position));
				setStrings.add(map.get("name"));
			}
			list.set(position, map);
			memberListAdapter.notifyDataSetChanged();//刷新listView
		}
	}


	//初始化团队成员的列表集合list
	public void initMembersList(){
		//验证时否联网
		if(!CheckedNetWork.checkedConnection(this)){
			return;
		}

		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("user_name", curUser);
		map1.put("teamName", curTeam);
		//		map1.put("action", "queryUser");
		map1.put("action", "queryTeamMember");
		String result = null;
		try {
			result = HttpUtil.postRequest(url1, map1);
			System.out.println("---------------------"+result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result==null) {
//			Toast.makeText(TaskActivity.this, "服务器未启动！", Toast.LENGTH_SHORT).show();
			return;
		}
		System.out.println("result = "+result);
		String[] string = new String[]{"user_picture","user_name","user_sex","user_email"};
		try {
			JSONObject object = new JSONObject(result);
			JSONArray array = object.getJSONArray("userListJson");
			System.out.println("*********"+array.toString());
			list.clear();
			for (int j = 0; j < array.length(); j++) {
				JSONObject object3 = array.getJSONObject(j);
				JSONArray array2 = object3.getJSONArray("userListJson"+j);
				System.out.println("*********"+array2.length());
				String url = array2.getJSONObject(0).getString(string[0]);
				String name = array2.getJSONObject(1).getString(string[1]);
				Map<String , String> map = new HashMap<String, String>();
				if (url.length() == 0) {
					map.put("url","");
					System.out.println("####"+map.get("url"));
				}else {
					map.put("url",url);
					System.out.println("####"+map.get("url"));
				}
				map.put("name", name);
				map.put("checked", "0");
				System.out.println("####"+map.get("name"));
				list.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		//刷新数据
		memberListAdapter.notifyDataSetChanged();
	}




	/**********fragment的滑动监听*************/
	public class My_vpOnPageChange implements OnPageChangeListener{
		@Override
		public void onPageSelected(int arg0) {
			/*if(my_vp.getCurrentItem()!=0){
				if(addTask.getVisibility()==View.VISIBLE){
					addTask.setVisibility(View.INVISIBLE);
				}
			}else {
				addTask.setVisibility(View.VISIBLE);
			}*/
			int curItem2 = my_vp.getCurrentItem();
			if(curItem2 == 0){
//				Toast.makeText(TaskActivity.this,"curItem = "+curItem2,Toast.LENGTH_LONG).show();
				Fragment1.initFragment1();
			}else if(curItem2==1){
//				Toast.makeText(TaskActivity.this,"curItem = "+curItem2,Toast.LENGTH_LONG).show();
				Fragment2.initFragment2();
			}else if(curItem2==2){
//				Toast.makeText(TaskActivity.this,"curItem = "+curItem2,Toast.LENGTH_LONG).show();
				Fragment3.initFragment3();
			}else {
//				Toast.makeText(TaskActivity.this, "获取当前页面Item异常！" , Toast.LENGTH_SHORT).show();
				return;
			}
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	}


	public class MyViewPagerAdapter extends FragmentPagerAdapter{
		public MyViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}
		@Override
		public Fragment getItem(int arg0) {
			return fragmentList.get(arg0);
		}
		@Override
		public int getCount() {
			return fragmentList.size();
		}
		@Override
		public CharSequence getPageTitle(int position) {
			return titleList.get(position);
		}
	}
}







